#!groovy

@Library('jenkinslib@master') _

def tools = new org.devops.tools()
def model = new org.devops.modules()
def dingmes = new org.devops.ding()
//gitlab仓库地址
String srcUrl = ""
//仓库分支
String branchName = ""
//微服务名称
String proName = ""
//环境
String instructions = "<font color=#FF0000>开发(全自动)</font>[查看日志](http://172.16.1.126:9900)"
//pm2 管理微服务--灰度发布
//#####################################
pm2_service_list = ["esign-base-sms-service","esign-base-seal-service","esign-base-realname-service","esign-base-distributed-file-service",
    "esign-base-certificate-service","esign-gateway-service","esign-auth-system","esign-platform-system","esign-log-service",
    "esign-tenant-info-service","esign-seal-service","esign-file-convert-service","esign-contract-template-service","esign-contract-service",
    "esign-certificate-service","esign-scan-code-service"]
pm2_status = "0"
//#####################################
//微服务部署服务器
def objhost = "172.16.1.126"
//#####################################
//临时存放在106的微服务
tmp106 = []
//#####################################
//指定微服务
String specified = ""
try{
    srcUrl = srcUrl_auto
    //只处理单服务
    proName = proName_auto.split('/')[0]
    specified = "2"
    //只处理dev
    if(ref.split('/')[-1] != "dev"){
        tools.PrintMes("只处理dev",'red')
        exit()
    }
    branchName = "dev"
    //只处理指定微服务
    arr = ["esign-base-sms-service","esign-base-seal-service","esign-base-realname-service","esign-base-distributed-file-service",
    "esign-base-certificate-service","esign-gateway-service","esign-auth-system","esign-platform-system","esign-log-service",
    "esign-tenant-info-service","esign-seal-service","esign-file-convert-service","esign-contract-template-service","esign-contract-service",
    "esign-certificate-service"]
    for (item in arr){
        if (item == proName){
            specified = "1"
        }
    }   
} catch (Exception e){
    tools.PrintMes("非自动化","blue")
    //gitlab仓库地址
    srcUrl = "${env.srcUrl}"
     srcUrl = srcUrl.split("\\(")[0].trim()
    //仓库分支
    branchName = "${env.branchName}"
    //微服务名称
    proName = "${env.proName}"
    proName = proName.split("\\(")[0].trim()
    //环境
    instructions = "开发(手动)[查看日志](http://172.16.1.126:9900)"
}
if(specified == "2"){
        tools.PrintMes("####################非指定微服务-自动化失败###################","blue")
        exit()
}
def workdir = ''
def pronames = ''
def mvn_com  = "/usr/bin/mvn"
//代码作者
def Author = ''
//更新记录(3条)
def ChangeLog = ''
//pipeline
pipeline{
    agent any    
    stages{

       stage("GetCode"){
            steps{
                script{
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        //判断是否存放于106服务器
                        for (item106 in tmp106){
                                if (item106 == proName){
                                    objhost = "172.16.1.106"
                                }
                        }   
                            
                        if(!workdir) {
                            println "获取工作目录失败"
                            exit()
                        }
                        tools.PrintMes("获取代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: '87886427-ebc2-4f45-8921-dcf38f80867e', url: "${srcUrl}"]]])
                        //代码作者
                        res = sh returnStdout: true ,script: "cd ${workdir}/${proName} && git log -1|grep Author |awk '{print \$2}'"
                        Author = res.trim()
                        //更新记录(5条)
                        tmp_shell="""
                            cd ${workdir}/${proName}
                            git log -3 |awk '!/^\$/' |awk '/^Author|^commit/ {next}{printf "%s\\n",\$0}'
                        """
                        res = sh returnStdout: true ,script: "${tmp_shell}"
                        ChangeLog = res.trim()
                        pronames = model.pronames(proName,workdir)
                        //创建jenkins临时目录
                        sh "mkdir -p ${workdir}/${proName}/jenkins_tmp"

                    }
            
                }
        }
        stage("Build&Test"){
            steps{
                script{
                    tools.PrintMes("mvn编译","green")
                        try{
                            sh "cd ${workdir} && cd ${proName} && ${buildShell}"
                            sh "exit 0"
                        }catch (Exception e){
                            tools.PrintMes("编译报错,尝试强制更新私库","blue")
                            sh "cd ${workdir} && cd ${proName} && mvn clean install -U package -X -Dmaven.test.skip=true"
                            sh "exit 0"
                        }  
                }
            }
        }
         stage("Deploy"){
            steps{
                script{
                    tools.PrintMes("部署","green")
                        sh "ssh root@${objhost} mkdir -p /data/before/${workdir}/${pronames}"
                        sh "ssh root@${objhost} rm -f /data/before/${workdir}/${pronames}/*.jar"
                        sh "scp ${workdir}/${proName}/target/*.jar root@${objhost}:/data/before/${workdir}/${pronames}"
                    res = sh returnStdout: true ,script: "ssh root@${objhost} \"cd /data/before/${workdir}/${pronames} && ls *.jar\""
                    res = res.trim()
                    /*config="""
                    #!/bin/bash
# jar包地址
PROJECT_PATH="${res}"
# 日志输出地址
PID=`ps -ef | grep \$PROJECT_PATH | grep -v grep | awk '{ print \$2 }'`
if [ -z "\$PID" ]
then
    echo Application is already stopped
else
    echo \$PROJECT_PATH
    echo kill \$PID
    kill -9 \$PID
fi
nohup java -jar \$PROJECT_PATH >nohup.log 2>&1 &
                    """
                    */
                    ///######################################
                        for (item in pm2_service_list){
        if (item == proName){
            config1="""
            {
    "apps": {                                                                           //json结构，数组类型，可以是多个，每个对应pm2中运行的应用
        "name": "${proName}",                                                  //pm2管理列表中显示的程序名称
        "script": "java",                                                       //使用语言指定为java
        "exec_mode": "fork",                                            //fork单例多进程模式，cluster多实例多进程模式只支持node
        "error_file": "err.log",                                    //错误日志存放位置
        "out_file": "out.log",                                  //全部日志存放位置
        "merge_logs": true,                                                     //追加日志
        "log_date_format": "YYYY/MM/DD HH:mm:ss",       //日志文件输出的日期格式
        "min_uptime": "60s",                                            //最小运行时间(范围内应用终止会触发异常退出而重启)
        "max_restarts": 30,                                                     //异常退出重启的次数
        "autorestart": true,                                            //发生异常情况自动重启
        "restart_delay": "60",                                          //异常重启的延时重启时间
        "args": [                                                                       //传递给脚本的java参数，有顺序限制
            "-jar",
            "-Xms512m",                                                  //JVM最大的内存
            "-Xmx512m",                                                 //JVM初始内存
            "${res}"                                               //执行参数之执行文件名
        ]
    }
}
            """
            writeFile(file: "${workdir}/${proName}/jenkins_tmp/start_jar.json", text: "${config1.trim()} ", encoding: "UTF-8")
            sh """
            scp ${workdir}/${proName}/jenkins_tmp/start_jar.json root@${objhost}:/data/before/${workdir}/${pronames}/start_jar.json
            """
            pm2_status = "1"
        }
}   
        if(pm2_status == "1"){
            sh "ssh root@${objhost} \"cd /data/before/${workdir}/${pronames};pm2 start start_jar.json\""
        }else{
                    //#######################################
                    //writeFile(file: "${workdir}/${proName}/jenkins_tmp/start_jar.sh", text: "${config.trim()} ", encoding: "UTF-8")
                   // sh "scp ${workdir}/${proName}/jenkins_tmp/start_jar.sh root@${objhost}:/data/before/${workdir}/${pronames}/start_jar.sh"
                    //result = sh returnStdout: true ,script: "ssh root@${objhost} \"cd /data/before/${workdir}/${pronames};chmod 777 start_jar.sh && ./start_jar.sh\""
        }
                    if(objhost == "172.16.1.126"){
                        result = sh returnStdout: true ,script: "ssh root@${objhost} \">/data/before/${workdir}/${pronames}/out.log;ln -fs /data/before/${workdir}/${pronames}/out.log /data/log-web/script/${pronames}.log\""
                    }
                    sh "exit 0"
                    tools.PrintMes("========部署成功========",'blue')
                }
            }
        }
    }
    post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq(pronames,'dev',"构建成功 ✅ ",Author,ChangeLog,pronames,instructions)
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq(pronames,'dev',"构建失败 ❌",Author,ChangeLog,pronames,instructions)
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq(pronames,'dev',"构建失败 ❌",Author,ChangeLog,pronames,"不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq(pronames,ImageTag,"构建失败 ❌",Author,ChangeLog,pronames,"暂停或中断")
                }
            }
        }
    
}
